package com.rongshe.web.controller.hotel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.rongshe.common.constant.MessageConstants;
import com.rongshe.common.core.domain.entity.SysUser;
import com.rongshe.common.utils.DateUtils;
import com.rongshe.hotel.domain.RsBooking;
import com.rongshe.system.domain.MessageDTO;
import com.rongshe.system.service.ISysMessageService;
import com.rongshe.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.rongshe.common.annotation.Log;
import com.rongshe.common.core.controller.BaseController;
import com.rongshe.common.core.domain.AjaxResult;
import com.rongshe.common.enums.BusinessType;
import com.rongshe.hotel.domain.RsOrder;
import com.rongshe.hotel.service.IRsOrderService;
import com.rongshe.common.utils.poi.ExcelUtil;
import com.rongshe.common.core.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author rongshe
 * @date 2025-02-17
 */
@RestController
@RequestMapping("/hotel/order")
public class RsOrderController extends BaseController
{
    @Autowired
    private IRsOrderService rsOrderService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(RsOrder rsOrder)
    {
        SysUser user = getLoginUser().getUser();
        if(null!= user.getUserType() && user.getUserType().equals("01")){
            rsOrder.setUserId(user.getUserId());
            if(rsOrder.getStatus().equals("1")){
                rsOrder.setStatus(null);
                rsOrder.setStatusIn("1,4");
            }
        }
        startPage();
        List<RsOrder> list = rsOrderService.selectRsOrderList(rsOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('hotel:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RsOrder rsOrder)
    {
        List<RsOrder> list = rsOrderService.selectRsOrderList(rsOrder);
        ExcelUtil<RsOrder> util = new ExcelUtil<RsOrder>(RsOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('hotel:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(rsOrderService.selectRsOrderById(id));
    }

    /**
     * 新增订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RsOrder rsOrder)
    {
        rsOrder.setUserId(getLoginUser().getUserId());
        rsOrder.setOrderTime(new Date());
        rsOrder.setStatus("1");
        int result = rsOrderService.insertRsOrder(rsOrder);
        createMessage(rsOrder.getId(),rsOrder.getStatus());
        return toAjax(result);
    }

    /**
     * 修改订单
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RsOrder rsOrder)
    {
        int result = rsOrderService.updateRsOrder(rsOrder);
        RsOrder rsOrder1 = rsOrderService.selectRsOrderById(rsOrder.getId());
//        createMessage(rsOrder1,rsOrder1.getStatus());
        return toAjax(result);
    }

    /**
     * 删除订单
     */
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(rsOrderService.deleteRsOrderByIds(ids));
    }

    @Autowired
    private ISysMessageService messageService;
    private void createMessage(Long rsOrderId, String status) {
        RsOrder rsOrder = rsOrderService.selectRsOrderById(rsOrderId);
        // 3. 构建消息内容
        String title = "";
        StringBuilder content = new StringBuilder();
        switch (status) {
            case "1": // 待出行
                title += "订单已下单通知";
                break;
            case "2": // 已完成
                title += "订单已完成通知";
                break;
            case "3": // 已取消
                title += "订单已取消通知";
                break;
            case "4": // 已确认
                title += "订单已接单通知";
                break;
            default:
                break;
        }
        content.append("下单时间：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, rsOrder.getOrderTime()) + "<br>");
        content.append("客户姓名：" + rsOrder.getUser().getUsername() + "<br>");
        content.append("客户电话：" + rsOrder.getUser().getUserPhone() + "<br>");
        content.append("订单总价：" + rsOrder.getTotal() + "<br>");

        // 4. 发送消息通知
        MessageDTO messageDTO = new MessageDTO();
        messageDTO.setTitle(title);
        messageDTO.setContent(content.toString());
        messageDTO.setInfoId(rsOrder.getId());
        messageDTO.setMessageType(MessageConstants.MESSAGE_TYPE_ORDER);    // 订单消息
        messageDTO.setSenderType(MessageConstants.SENDER_TYPE_SYSTEM);     // 系统发送
        messageDTO.setImportance(MessageConstants.IMPORTANCE_NORMAL);   // 重要消息
        List<SysUser> sysUsers = userService.selectWebUserList();
        List<Long> receiverIds = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
        messageDTO.setReceiverIds(receiverIds);

        messageService.sendMessage(messageDTO);
    }
}
